 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmAlipayQrConsumeTmp;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmAlipayQrConsume;
import com.zdkj.subway.rca.mapper.SwCkStatementConfirmAlipayQrConsumeTmpMapper;
import com.zdkj.subway.rca.service.SwCkStatementConfirmAlipayQrConsumeTmpService;
import com.zdkj.subway.rca.service.SwCkStatementConfirmAlipayQrConsumeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 西安地铁支付宝二维码消费过闸确认临时表
 *
 * @author stw
 * @date 2020-10-24 13:51:35
 */
@Service
public class SwCkStatementConfirmAlipayQrConsumeTmpServiceImpl extends ServiceImpl<SwCkStatementConfirmAlipayQrConsumeTmpMapper, SwCkStatementConfirmAlipayQrConsumeTmp> implements SwCkStatementConfirmAlipayQrConsumeTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkStatementConfirmAlipayQrConsumeTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd HH:mm:ss";
    @Autowired
    private SwCkStatementConfirmAlipayQrConsumeService swCkStatementConfirmAlipayQrConsumeService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(3).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkStatementConfirmAlipayQrConsumeTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                SwCkStatementConfirmAlipayQrConsumeTmp tmpObj = new SwCkStatementConfirmAlipayQrConsumeTmp();
                tmpObj.setTradeDateTmp(data.get(0));//交易日期
                tmpObj.setTotalCountTmp(data.get(1));
                tmpObj.setTotalMoneyTmp(data.get(2));
                tmpObj.setTotalServiceChargeTmp(data.get(3));
                tmpObj.setConsumeCountTmp(data.get(4));
                tmpObj.setConsumeMoneyTmp(data.get(5));
                tmpObj.setConsumeServiceChargeTmp(data.get(6));
                tmpObj.setZfmCountTmp(data.get(7));
                tmpObj.setZfmMoneyTmp(data.get(8));
                tmpObj.setZfmServiceChargeTmp(data.get(9));

                if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalCountTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalMoneyTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalServiceChargeTmp())
                        ) {
                    continue;
                }
                if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }

                final SwCkStatementConfirmAlipayQrConsumeTmp obj = ObjectUtils.getDefaultObj(SwCkStatementConfirmAlipayQrConsumeTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj);
                listDb.add(obj);

            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);

        }

        return false;
    }

    private void checkErr(SwCkStatementConfirmAlipayQrConsumeTmp obj) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        try {
            String totalCountTmp = obj.getTotalCountTmp();
            Long totalCount = Long.parseLong(totalCountTmp);
            obj.setTotalCount(totalCount);

            String consumeCountTmp = obj.getConsumeCountTmp();
            Long consumeCount = Long.parseLong(consumeCountTmp);
            obj.setConsumeCount(consumeCount);

            String zfmCountTmp = obj.getZfmCountTmp();
            Long zfmCount = Long.parseLong(zfmCountTmp);
            obj.setZfmCount(zfmCount);


        } catch (Exception e) {
            obj.setErrMsg("笔数 为空或格式错误");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String totalMoneyTmp = obj.getTotalMoneyTmp();
            BigDecimal totalMoney = new BigDecimal(totalMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            totalMoney = totalMoney.multiply(num);
            obj.setTotalMoney(totalMoney.longValue());

            String consumeMoneyTmp = obj.getConsumeMoneyTmp();
            BigDecimal consumeMoney = new BigDecimal(consumeMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);

            consumeMoney = consumeMoney.multiply(num);
            obj.setConsumeMoney(consumeMoney.longValue());

            String zfmMoneyTmp = obj.getZfmMoneyTmp();
            BigDecimal zfmMoney = new BigDecimal(zfmMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            zfmMoney = zfmMoney.multiply(num);
            obj.setZfmMoney(zfmMoney.longValue());


        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String totalServiceChargeTmp = obj.getTotalServiceChargeTmp();
            BigDecimal totalServiceCharge = new BigDecimal(totalServiceChargeTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            totalServiceCharge = totalServiceCharge.multiply(num);
            obj.setTotalServiceCharge(totalServiceCharge.longValue());

            String consumeServiceChargeTmp = obj.getConsumeServiceChargeTmp();
            BigDecimal consumeServiceCharge = new BigDecimal(consumeServiceChargeTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            consumeServiceCharge = consumeServiceCharge.multiply(num);
            obj.setConsumeServiceCharge(consumeServiceCharge.longValue());

            String zfmServiceChargeTmp = obj.getZfmServiceChargeTmp();
            BigDecimal zfmServiceCharge = new BigDecimal(zfmServiceChargeTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            zfmServiceCharge = zfmServiceCharge.multiply(num);
            obj.setZfmServiceCharge(zfmServiceCharge.longValue());

        } catch (Exception e) {
            obj.setErrMsg("手续费 为空或格式错误");
        }

        //判断数据是否存在
        SwCkStatementConfirmAlipayQrConsume SwCkStatementConfirmAlipayQrConsume = new SwCkStatementConfirmAlipayQrConsume();
        BeanUtils.copyProperties(obj, SwCkStatementConfirmAlipayQrConsume, "deptId","creatorId","creatorName","createTime");
        List<SwCkStatementConfirmAlipayQrConsume> list = swCkStatementConfirmAlipayQrConsumeService.list(Wrappers.query(SwCkStatementConfirmAlipayQrConsume));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
